package cn.edu.xmu.rocketmqdemo.service;

import cn.edu.xmu.rocketmqdemo.model.Order;
import cn.edu.xmu.rocketmqdemo.model.OrderVo;
import cn.edu.xmu.rocketmqdemo.model.VoObject;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import cn.edu.xmu.rocketmqdemo.model.Log;
import cn.edu.xmu.rocketmqdemo.util.*;
/**
 * @author Ming Qiu
 * @date Created in 2020/11/7 22:53
 **/
@Service
public class RocketMQService { //生产者代码

    private static final Logger logger = LoggerFactory.getLogger(RocketMQService.class);

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Value("${rocketmqdemo.order-pay-topic.delay-level}")
    private int delayLevel;

    @Value("${rocketmqdemo.order-pay-topic.timeout}")
    private long timeout;

    private ReturnObject<VoObject> returnVo;

    public ReturnObject<VoObject> getReturnVo() {
        return returnVo;
    }

    public void sendOrderMessage(OrderVo orderVo){//生产者发送要提交的order。消费者负责存入数据库

        rocketMQTemplate.asyncSend("order-topic",  MessageBuilder.withPayload(JacksonUtil.toJson(orderVo)).build(), new SendCallback() {//通过topic找到关联的消费者
            @Override
            public void onSuccess(SendResult sendResult) {
                returnVo = new ReturnObject<>(ResponseCode.OK);
            }
            @Override
            public void onException(Throwable throwable) {
             returnVo = new ReturnObject<>(ResponseCode.FIELD_NOTVALID,throwable.getMessage());
            }
        },1000*timeout,delayLevel);
    }

}
